import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  SafeAreaView,
  ImageBackground,
  PixelRatio,
  TouchableOpacity,
  Linking
} from 'react-native';
import {
  iconUserCoffee,
  iconUserGray,
  avatarDefault,
  iconDriveTruckBlack,
  iconProtocolBlack,
  iconDriverGray,
  iconDriverGreen,
  iconSettingBlack,
  iconLockBlack,
  iconServiceBlack,
  iconRightGray02,
  iconOilCardBlack,
  iconWaterCamera,
  iconAdviseBlack
} from '@/images';
import { msg, AsyncStorage, cache } from '@/common';
import { ListItem } from '@/components';
import {
  px2dp,
  mainBgColorLightGray,
  mainBgColorWhite,
  screenWidth,
  fontColorDeepGreen,
  fontColorLightGreen,
  fontColorSecDeepGray,
  fontColorDeepGray,
} from '@/styles';
import api from '@/api';
import baseConfig from '@/config/baseConfig';

const { fileUrl } = baseConfig;

export default class User extends React.Component {
  static navigationOptions = () => ({
    title: '我的',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconUserCoffee : iconUserGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      avatarId: '',
      name: '',
      certState: 0,
      certFailSeason: '',
      serviceNumber: '', // 客服电话
    };
  }

  componentDidMount() {
    this.getInfo();
    this.getDriverCertInfo();
    AsyncStorage.getItem(cache.SERVICE_NUMBER).then((res) => {
      this.setState({ serviceNumber: res });
    });
  }

  render() {
    const { avatarId, name, certState, serviceNumber } = this.state;
    console.log('🚀🚀🚀wimi======>>>avatarId', avatarId);
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.headerContainer}>
          <TouchableOpacity
            style={styles.settingWrap}
            onPress={() => this.goToSetting()}
          >
            <Image style={styles.settingImg} source={iconSettingBlack} />
          </TouchableOpacity>
          <ImageBackground
            style={styles.bgStyle}
            source={require('@/images/wl/driver_head_bg.png')}
            resizeMode='contain'
          >
            <Image
              style={styles.shipperAvartar}
              source={avatarId ? { uri: fileUrl + avatarId } : avatarDefault}
            />
            <TouchableOpacity
              style={styles.headerRight}
              activeOpacity={0.8}
              onPress={() => {
                msg.emit('router: goToNext', {
                  routeName: 'CertificationProgress',
                });
              }}
            >
              <Text style={styles.headerName}>
                {name}
              </Text>
              <View style={[styles.certWrap, certState === 2 && { backgroundColor: fontColorLightGreen, borderColor: fontColorDeepGreen, width: px2dp(158) }]}>
                <Image style={styles.certIcon} source={certState === 2 ? iconDriverGreen : iconDriverGray} />
                <Text style={[styles.certTip, certState === 2 && { color: fontColorDeepGreen }]}>认证司机</Text>
                {certState !== 2 && <Image style={styles.certIcon} source={iconRightGray02} />}
              </View>
            </TouchableOpacity>
          </ImageBackground>
        </View>

        <View style={styles.boxWrap}>
          <ListItem
            title='驾驶车辆'
            icon={iconDriveTruckBlack}
            onClick={this.driveTruck}
          />

          {/* <ListItem
            title='修理卡'
            icon={iconRepairCardBlack}
            onClick={this.goToRepairCard}
          /> */}
          <ListItem
            title='缘多用油'
            icon={iconOilCardBlack}
            onClick={this.goToOilCardPlatform}
          />
          <ListItem
            title='合同及协议'
            icon={iconProtocolBlack}
            onClick={this.wlProtocal}
          />
          <ListItem
            title='历史相册'
            icon={iconWaterCamera}
            onClick={this.goToWatermarkCameraHistoryRecords}
            rightBoxStyle={{ borderBottomWidth: 0 }}
          />

        </View>
        <View style={styles.boxWrap}>
          <ListItem
            title='账号安全'
            icon={iconLockBlack}
            onClick={this.goToAccountCenter}
          />
          <ListItem
            title='客服热线'
            extra={serviceNumber}
            icon={iconServiceBlack}
            onClick={this.callServicePhone}
          />

          <ListItem
            title='意见反馈'
            icon={iconAdviseBlack}
            onClick={this.goToUserFeedBack}
            rightBoxStyle={{ borderBottomWidth: 0 }}
          />
        </View>
      </SafeAreaView>
    );
  }

  goToUserFeedBack = () => {
    msg.emit('router: goToNext', {
      routeName: 'UserFeedback',
    });
  };

  goToSetting = () => {
    msg.emit('router: goToNext', {
      routeName: 'Setting',
    });
  };

  goToAccountCenter = () => {
    msg.emit('router: goToNext', {
      routeName: 'AccountCenter',
    });
  };

  callServicePhone = () => {
    const { serviceNumber } = this.state;
    if (serviceNumber.length <= 0) return;
    const url = `tel:${serviceNumber}`;
    Linking.canOpenURL(url)
      .then((supported) => {
        if (!supported) {
          NativeModules.WindowModule.showWindow(
            {
              content: `您的设备不支持该功能，请手动拨打${phone}`,
              onlyRightBtn: '1',
            },
            (e) => {
              console.log('🚀🚀🚀wimi======>>>e', e);
            },
          );
          return;
        }
        return Linking.openURL(url);
      })
      .catch((err) => {
        msg.emit('app:tip', { text: err });
      });
  };

  // 查询用户信息
  getInfo() {
    api.user.getUserInfo().then((res) => {
      if (res.success && res.data) {
        this.setState({
          avatarId: res.data.avatarId,
          name: res.data.name,
        });
      }
    });
  }

  // 查询认证状态
  getDriverCertInfo() {
    api.supply.getDriverCer().then((res) => {
      if (res.success) {
        this.setState({
          certState: res.data.state,
          certFailSeason: res.data.descrption,
        });
      }
    });
  }

  showCertViewColor = () => {
    const { certState } = this.state;
    switch (certState) {
    case 0:
      return '#999796';
    case 1:
      return '#BA914A';
    case 3:
      return '#EB2F2F';
    case 2:
      return '#999796';
    default:
      return '#EB2F2F';
    }
  };

  showCertViewTip = () => {
    const { certState } = this.state;
    switch (certState) {
    case 0:
      return '未认证';
    case 1:
      return '待认证';
    case 3:
      return '已拒绝';
    case 2:
      return '已通过';
    default:
      return '';
    }
  };

  driverCert = () => {
    const { certState, certFailSeason } = this.state;
    if (certState === 3) return;
    if (certState === 0) {
      msg.emit('router: goToNext', {
        routeName: 'DriverCer',
        routerFrom: 'DriverUser',
      });
    }
    if (certState === 1) {
      msg.emit('router: goToNext', {
        routeName: 'FeedBackDriverCer',
        status: 1,
        title: '司机认证已提交审核',
        desc: '工作人员将在3个工作日内给予答复',
        routerFrom: 'DriverUser',
      });
    }
    if (certState === 2) {
      msg.emit('router: goToNext', {
        routeName: 'FeedBackDriverCer',
        status: 0,
        title: '非常抱歉，您未能通过认证',
        desc: `原因：${certFailSeason}`,
        routerFrom: 'DriverUser',
        routerTo: 'DriverCer',
      });
    }
  };

  driveTruck = () => {
    api.supply.getDriverCarDetail().then((res) => {
      if (res.success) {
        if (res.data) {
          let infoData = {
            vehiclePhoto: '',
            numberPlates: res.data.carNo, // 车牌号
            joinTime: res.data.createTime, // 入住时间
            driveAge: res.data.age, // 驾龄
            vehicleModel: res.data.carType, // 车型
            vehicleLong: res.data.vehicleLength, // 车长
            load: res.data.vehicleTonnage, // 载重
            ascriptionEnterprise: res.data.legalName, // 所属企业
            cooperateType: res.data.vehicleCoopType, // 合作类型
            obdStatus: res.data.obdStatus, // obd信息
            obdInfo: res.data.obdInfo, // obd信息
            vehicleEquipment: '', // 车载设备
          };
          msg.emit('router: goToNext', {
            routeName: 'VehicleInfo',
            infoData,
          });
        } else {
          msg.emit('router: goToNext', {
            routeName: 'VehicleInfo',
            infoData: null,
          });
        }
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  goToRepairCard = () => {
    msg.emit('router: goToNext', {
      routeName: 'WlRepair',
    });
  };

  goToOilCardPlatform = () => {
    msg.emit('router: goToNext', {
      routeName: 'OilCardPlatform',
    });
  };

  goToWatermarkCameraHistoryRecords = () => {
    msg.emit('router: goToNext', {
      routeName: 'WatermarkCameraHistoryRecords',
    });
  };

  wlProtocal = () => {
    msg.emit('router: goToNext', {
      routeName: 'ContractSYSList',
      // routerFrom: 'logiticsAgreement',
    });
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
  },
  headerContainer: {
    width: screenWidth,
    height: px2dp(312),
    backgroundColor: mainBgColorWhite,
    position: 'relative',
  },
  bgStyle: {
    width: '100%',
    height: px2dp(312),
    paddingTop: px2dp(88),
    flexDirection: 'row',
    alignItems: 'center',
  },
  shipperAvartar: {
    width: px2dp(135),
    height: px2dp(135),
    borderRadius: px2dp(270),
    borderColor: '#F5F5F5',
    borderWidth: px2dp(13),
    marginHorizontal: px2dp(32),
  },

  headerRight: {},
  headerName: {
    fontSize: px2dp(42),
    fontWeight: 'bold',
  },

  certWrap: {
    width: px2dp(184),
    height: px2dp(48),
    borderRadius: px2dp(24),
    borderWidth: 1 / PixelRatio.get(),
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: px2dp(16),
    marginTop: px2dp(16),
    borderColor: fontColorSecDeepGray,
    // backgroundColor: fontColorSecDeepGray,
  },
  certIcon: {
    width: px2dp(24),
    height: px2dp(24),
  },
  certTip: {
    color: fontColorDeepGray,
    fontSize: px2dp(24),
    marginLeft: px2dp(4),
  },
  settingWrap: {
    width: px2dp(110),
    height: px2dp(88),
    right: px2dp(0),
    top: px2dp(0),
    position: 'absolute',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 10,
  },
  settingImg: {
    width: px2dp(46),
    height: px2dp(46),
  },

  boxWrap: {
    paddingHorizontal: px2dp(32),
    backgroundColor: mainBgColorWhite,
    marginTop: px2dp(16),
  },

  certFlag: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(24),
    backgroundColor: '#E9F8E9',
    paddingLeft: px2dp(16),
    paddingTop: px2dp(5),
    paddingRight: px2dp(16),
    paddingBottom: px2dp(5),
    borderRadius: px2dp(28),
  },

  pl0: {
    paddingLeft: 0,
  },
  mr0: {
    marginRight: px2dp(64),
  },
  mt16: {
    marginTop: px2dp(16),
  },
});
